<template>
  <div class="container">
    <table>
      <thead>
        <tr>
          <th v-for="(item, idx) in tableHead" :key="idx">
            {{ item }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in data" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.bookName }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="item.count > 0 && item.count--">-</button>
            <input
              type="text"
              :value="item.count"
              @input="(e) => checkInp(e, item)"
              @blur="onBlur"
            >
            <button @click="item.count++">+</button>
          </td>
          <td>{{ item.price * item.count }}</td>
        </tr>
      </tbody>
    </table>
    <div class="total">
      总价格为: {{ total }}
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      tableHead: ['序号', '书名', '单价', '数量', '合计'],
      data: [
        {
          id: 1,
          bookName: '水浒传',
          price: 50,
          count: 0,
        },
        {
          id: 2,
          bookName: '西游记',
          price: 100,
          count: 0,
        },
        {
          id: 3,
          bookName: '三国',
          price: 200,
          count: 0,
        },
        {
          id: 4,
          bookName: '红楼梦',
          price: 300,
          count: 0,
        },
      ],
    };
  },
  computed: {
    total () {
      return this.data.reduce((prev, current) => prev + current.price * current.count, 0);
    },
  },
  methods: {
    checkNum (arr) {
      return arr.every(item => !isNaN(item.count));
    },
    checkInp (e, item) {
      if (!isNaN(e.target.value)) {
        item.count = Number(e.target.value);
      }
    },
    onBlur () {
      this.data = this.data.concat();
    },
  },
}
</script>

<style scoped>

</style>